<template>
    <a-card :bordered="false">
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row style="display: flex;position: absolute;right: 20px;">
                    <a-col :md="24" :sm="24">
                        日期区间:{{ startRange }}{{ endRange ? '~' : '' }}{{ endRange }}
                    </a-col>
                </a-row>
                <a-row :gutter="10">
                    <!-- <a-col :md="4" :sm="24">
                        <a-form-item label="查询类别">
                            <a-select v-model="queryParam.condition" allowClear>
                                <a-select-option key="code">编码</a-select-option>
                                <a-select-option key="name">名称</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col> -->
                    <a-col :md="4" :sm="24">
                        <a-form-item label="产品名称">
                            <a-input v-model="queryParam.Product" placeholder="请输入产品名称" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <!-- <a-col :md="4" :sm="24">
                        <a-form-item label="选择仓库">
                            <a-select ref="select" placeholder="请选择仓库" v-model:value="queryParam.Warehouse">
                                <a-select-option v-for="item in selectOption" :key="item.code" :value="item.code">{{
                                    item.name }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col> -->
                    <a-col :md="14" :sm="24">
                        <a-select style="width: 100px;margin-left: 8px;" v-model="selectTime" @change="changeTime"
                            name="radioGroup" :default-value="0">
                            <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                                {{ i }}
                            </a-select-option>
                        </a-select>
                        <a-range-picker style="width: 220px;margin-left: 8px;" :placeholder="['开始月份', '结束月份']"
                            format="YYYY-MM" :value="time" :mode="['month', 'month']" :open="monthPickShow"
                            @panelChange="handlePanelChange2" :disabled="timeDisabled" @openChange="handleOpenChange" />
                        <!-- <a-range-picker style="margin-left: 8px;width: 220px;" :disabled="timeDisabled" v-model="time" /> -->
                        <a-button style="margin-left: 10px;" type="primary" @click="() => {
                            this.pagination.current = 1
                            this.getDataList()
                        }
                            ">查询
                        </a-button>
                        <a-button style="margin-left: 8px;margin-right: 8px;" @click="repossess">重置</a-button>
                        <a-button type="primary" icon="download" @click="downloadTemplate">导出</a-button>
                    </a-col>
                </a-row>
            </a-form>
        </div>

        <a-table ref="table" :bordered="true" :columns="columns" :dataSource="data" :loading="loading"
            :pagination="pagination" :scroll="{ y: 530 }" size="small" @change="handleTableChange">
            <!-- <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span> -->
            <!-- <span slot="action" slot-scope="text, record">
                <template>
                    <a @click="handleEdit(record)">查看</a>
                    <a-divider v-if="hasPerm('SO_SOMain.Edit') && hasPerm('SO_SOMain.Delete')" type="vertical" />
                    <a v-if="hasPerm('SO_SOMain.Delete')" @click="handleDelete([record.Id])">删除</a>
                </template>
            </span> -->
        </a-table>
        <div style="display: flex;position: absolute;bottom: 25px;">
            <p>总售价:{{ entity.TotalPrice }}</p>
            <p style="margin: 0 20px;">总成本:{{ entity.TotalChengben }}</p>
            <p>总毛利:{{ entity.TotalMaoli }}</p>
        </div>
    </a-card>
</template>

<script>
import Token from '@/utils/cache/TokenCache'
import moment from 'moment'
import { download } from '@/components/download'

const columns = [
    // { title: '', dataIndex: 'SalesOrderNo', },
    // {
    //     title: '日期',
    //     dataIndex: 'time',
    //     align: 'center',
    //     customRender: (value, row) => {
    //         return row.time.substring(0, 10)
    //     },

    // },
    { title: '产品名称', dataIndex: 'name', },
    { title: '规格', dataIndex: 'specification', },
    { title: '仓库', dataIndex: 'Warehouse', },
    { title: '计量单位', dataIndex: 'UnitName',width:'80px' },
    { title: '数量', dataIndex: 'InvoicingQuantity', align: 'right',width:'100px' },
    { title: '售价', dataIndex: 'InvoicingAmount', align: 'right',width:'100px' },
    { title: '成本单价', dataIndex: 'Price', align: 'right',width:'100px' },
    { title: '成本', dataIndex: 'chengben', align: 'right',width:'100px' },
    { title: '毛利', dataIndex: 'maoli', align: 'right',width:'100px' },
    // { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, }
]

export default {
    components: {
        Token
    },
    mounted() {
        this.$nextTick(() => {
            // 页面渲染完成后的回调
            // this.tableHeight = this.getTableHeight(true) + 24
            this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
            this.getDataList()

            // this.getSelectOptions();
        })
    },
    data() {
        return {
            headers: {
                authorization: 'Bearer ' + Token.getToken()
            },
            data: [],
            monthPickShow: false,
            entity: {},
            visible: false,
            pagination: {
                current: 1,
                pageSize: 25,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            filters: {},
            sorter: { field: 'dDate', order: 'desc' },
            loading: false,
            selectOption: [],
            columns,
            queryParam: { Warehouse: '02' },
            visibleUpload: false,
            selectedRowKeys: [],
            time: [],
            timeDisabled: true,
            selectTime: 0,
        }
    },
    computed: {
        startRange() {
            if (!this.time[0]) {
                return ''
            }
            const currentDate = new Date(this.time[0]); // 获取当前日期
            const previousMonth = (currentDate.getMonth() === 0) ? 12 : currentDate.getMonth(); // 如果当前月份是1月，则上个月是12月，否则上个月就是当前月份减一
            return `${currentDate.getMonth() === 0 ? new Date().getFullYear(this.time[0]) - 1 : new Date().getFullYear(this.time[0])}-${previousMonth}-26`
        },
        endRange() {
            if (!this.time[1]) {
                return ''
            }
            const currentDate = new Date(this.time[1]); // 获取当前日期
            const previousMonth = currentDate.getMonth() + 1; // 如果当前月份是1月，则上个月是12月，否则上个月就是当前月份减一
            return `${new Date().getFullYear(this.time[1])}-${previousMonth}-25`
        }
    },
    methods: {
        openhtml() {
            this.$http.post('/OrderManagement/SO_SOMain/ExportSO_SOMainAndRuleToExcel', {}).then(resJson => {
                if (resJson.Success) {
                    download(resJson.Data.fileUrl, resJson.Data.fileName)
                    this.visible = false
                } else {
                    this.$message.error(resJson.Msg)
                }
            })
        },
        repossess() {
            this.queryParam = { Warehouse: '02' }
            this.changeTime(0);
            this.getDataList();
        },
        handleTableChange(pagination, filters, sorter) {
            this.pagination = { ...pagination }
            this.filters = { ...filters }

            this.getDataList()
        },
        handlePanelChange2(value) {
            if (this.time[1] && this.time._d != value[1]._d) {
                this.monthPickShow = false;
            }
            this.time = value;
        },
        handleOpenChange(status) {
            if (status) {
                this.monthPickShow = true;
            } else {
                this.monthPickShow = false
            }
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        getDataAll() {
            this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetGrossProfitTotal', { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" }).then(res => {
                if (res.Success) {
                    this.entity = res.Data;
                }
            }).catch(err => {
                this.$message.error(err);
            })
        },
        async getDataList() {
            if (!this.time[1]) {
                this.$message.error('请先选择日期区间')
                return;
            }
            this.selectedRowKeys = []
            // this.queryParam.condition='name'
            this.loading = true
            await this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetCostPrice', { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" })
            this.$http
                .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetGrossProfit', {
                    PageIndex: this.pagination.current,
                    PageRows: this.pagination.pageSize,
                    Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" },
                })
                .then(resJson => {
                    this.loading = false
                    this.data = resJson.Data
                    this.data.forEach(item => {
                        item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
                        item.chengben = this.$options.filters.NumberFormats(item.chengben)
                        item.maoli = this.$options.filters.NumberFormats(item.maoli)
                        item.InvoicingQuantity = item.InvoicingQuantity.toFixed('4')

                    })

                    if (this.data) {
                        const pagination = { ...this.pagination }
                        pagination.total = resJson.Total
                        this.pagination = pagination
                    }
                    this.getDataAll()
                }).catch(err => {
                    this.$message.error(err);
                })
        },
        // 导入文件类型
        handleChange(info) {
            if (info.file.status !== 'uploading') {
            }
            if (info.file.status === 'done') {
                if (info.file.response.Success === false) {
                    this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
                } else {
                    this.$message.success(`${info.file.name}  文件上传成功！`)
                    this.getDataList()
                }
                this.visible = false
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 文件上传失败！`)
            }
        },
        hasSelected() {
            return this.selectedRowKeys.length > 0
        },
        handleAdd() {
            this.$refs.editForm.openForm(null, '新建销售订单主表信息')
        },
        handleEdit(id) {
            this.$refs.editForm.openForm(id, '订单详情')
        },
        //导入
        handleImport() {
            this.visibleUpload = true;
        },
        //导出
        downloadTemplate() {
            this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/Export', {
                Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : "", EndTime: this.time[1] ? this.timeFormat(this.time[1]) : "" },
            }, { responseType: 'blob' }).then(res => {
                const url = URL.createObjectURL(res)
                // console.log(url)
                const fileName = '销售毛利表'
                const aTag = document.createElement('a')
                aTag.download = fileName
                aTag.href = url
                aTag.click()
                URL.revokeObjectURL(aTag.href)
            }).catch(err => {
                this.$message.error(err);
            })
        },
        getSelectOptions() {
            this.$http.post('InvoiceManagement/Inv_InvoiceApplyMain/GetWarehouseList').then(res => {
                this.selectOption = res.Data;
            }).catch(err => {
                this.$message.error(err);
            })
        },
        handleDelete(ids) {
            var thisObj = this
            // this.$confirm({
            //   title: '确认删除吗?',
            //   onOk() {
            //     return new Promise((resolve, reject) => {
            //       thisObj.$http.post('/OrderManagement/SO_SOMain/DeleteData', ids).then(resJson => {
            //         resolve()

            //         if (resJson.Success) {
            //           thisObj.$message.success('操作成功!')

            //           thisObj.getDataList()
            //         } else {
            //           thisObj.$message.error(resJson.Msg)
            //         }
            //       })
            //     })
            //   }
            // })

            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                thisObj.$http
                    .post('/OrderManagement/SO_SOMain/DeleteData', ids)
                    .then(resJson => {
                        // resolve()

                        if (resJson.Success) {
                            thisObj.$message.success('操作成功!')

                            thisObj.getDataList()
                        } else {
                            thisObj.$message.error(resJson.Msg)
                        }
                    })
            })
        },
        changeTime(e) {
            this.timeDisabled = true;
            this.selectTime = e;
            this.time = [];
            switch (e) {
                case 0:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 1:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 2:
                    this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
                    this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
                    break
                case 3:
                    this.timeDisabled = false;
                    break
            }
        },
        timeFormat(val) {
            // 时间格式化函数
            return moment(val).format('YYYY-MM')
        }
    }
}
</script>

<style scoped>
.flax {
    display: flex;
    justify-content: space-between;
}

/* .download {
  float: right;
  display: flex;
  align-items: center;
} */
</style>